
import os, sys
from Sanae3D.lib.ModelObject import Model3D
from Sanae3D.lib.StructReader import StructReader

class Illusion_XA(Model3D):
    
    def __init__(self, obj3D=None, outFile=None, inFile=None):
        
        super(Illusion_XA,self).__init__("XA")
        self.obj3D = obj3D
        self.inFile = inFile
        self.outFile = outFile
        
    def check_header(self):
        
        self.xaType = self.inFile.read_ubyte()
        if self.xaType == 0x00:
            return False
        elif self.xaType in [0x02, 0x03]:
            return True
        elif self.xaType == 0x01:
            test = self.inFile.read_ubyte()
            if test > 0x01:
                return False
            else:
                if test == 0x01:
                    self.inFile.read_ubyte(3)
                    
    def read_name(self):
        
        print self.inFile.tell()
        name = bytearray(self.inFile.read_string(64))
        for i in range(64):
            name[i] = name[i] ^ 0xFF
        print ''.join(name)
                    
    def parse_material_section(self):
        
        pass
    
    def parse_unk(self):
        
        pass
    
    def parse_morphs(self):
        
        pass
    
    def parse_animations(self):
        
        if self.xaType == 0x03:
            numClips = 1024
        else:
            numClips = 512
        
        #for i in xrange(numClips):
        clipName = self.read_name()
        self.inFile.read_ubyte(44)
            
        numAnim = self.inFile.read_ulong()
        print numAnim
        
    def parse_file(self):
        '''Main parser method. Can be replaced'''
        
        isValid = self.check_header()
        
        if isValid:
            headerType = self.inFile.read_long()
            headerUnk = self.inFile.read_ubyte()
            
        sections = self.inFile.read_ubyte(4)
        
        if sections[0]:
            self.parse_materials()
        if sections[1]:
            self.parse_unk()
        if sections[2]:
            self.parse_morphs()
        if sections[3]:
            self.parse_animations()
            
        
def read_file(path):
    '''Read the file'''
    
    openFile = StructReader(open(path, 'rb'))
    obj = Illusion_XA(inFile=openFile)
    obj.parse_file()
    openFile.close()
    return obj

def write_file(path):
    
    pass

def definitions():
    '''Return the header, extension, and a description of the format'''
    
    return "", "XA", "Illusion XA"

if __name__ == '__main__':
    
    file1 = ""
    obj = read_file(file1)